<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import type { UnwrapRef } from 'vue';
import { Modal, message } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import ExcelJS from 'exceljs';
import type dayjs from 'dayjs';
import { useDownExcel } from './useDownExcel';
import { useUpload } from './useUpload';
import { useKPIHistoryStore } from '@/store/modules/dcp/assessment_indicators/kpi_history';

const dataTitle = ref<string>('2024年7月数据');
const allColumns: any = [
  {
    title: '考核项目',
    dataIndex: 'evaluationItem',
    key: 'evaluationItem',
    width: '8%',
    align: 'center',
    fixed: 'left',
    customCell: (record: any) => {
      const rowSpan = record.evaluationItemRowSpan || 1;
      return {
        rowSpan: rowSpan > 0 ? rowSpan : undefined,
        style: record.style || {}, // 使用我们设置的样式
      };
    },
  },
  {
    title: dataTitle.value,
    align: 'center',
    children: [
      {
        title: '大指标',
        dataIndex: 'mainIndicator',
        width: '8%',
        key: 'mainIndicator',
        align: 'center',
      },
      {
        title: '大指标分值',
        dataIndex: 'mainIndicatorScore',
        width: '5%',
        key: 'mainIndicatorScore',
        align: 'center',
      },
      {
        title: '考核部门的提供部门和取数据的系统',
        dataIndex: 'dataProvisionDepartment',
        width: '8%',
        key: 'dataProvisionDepartment',
        align: 'center',
      },
      {
        title: '考核周期',
        dataIndex: 'evaluationPeriod',
        width: '5%',
        key: 'evaluationPeriod',
        align: 'center',
      },
      {
        title: '目标值',
        dataIndex: 'targetValue',
        key: 'targetValue',
        width: '10%',
        align: 'center',
      },
      {
        title: '指标定义(解释)',
        dataIndex: 'indicatorDefinition',
        key: 'indicatorDefinition',
        width: '20%',
        align: 'center',
      },
      {
        title: '扣加分方法',
        dataIndex: 'deductionAdditionMethod',
        key: 'deductionAdditionMethod',
        width: '20%',
        align: 'center',
      },
    ],
  },
  {
    title: '2024年7月数据',
    align: 'center',
    children: [
      {
        title: '越城',
        dataIndex: 'yuecheng',
        key: 'yuecheng',
        width: '5%',
        align: 'center',
      },
      {
        title: '柯桥',
        dataIndex: 'keqiao',
        key: 'keqiao',
        width: '5%',
        align: 'center',
      },
      {
        title: '上虞',
        dataIndex: 'shangyu',
        key: 'shangyu',
        width: '5%',
        align: 'center',
      },
      {
        title: '嵊州',
        dataIndex: 'shengzhou',
        key: 'shengzhou',
        width: '5%',
        align: 'center',
      },
      {
        title: '新昌',
        dataIndex: 'xinchang',
        key: 'xinchang',
        width: '5%',
        align: 'center',
      },
      {
        title: '诸暨',
        dataIndex: 'zhuji',
        key: 'zhuji',
        width: '5%',
        align: 'center',
      },
    ],
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: '10%',
    fixed: 'right',
    align: 'center',
  },
];
const { auth } = useAuth();
function showRoleColumn() {
  return auth([
    'a_i_edit',
  ]);
}
const columns: any = computed(() => {
  return allColumns.filter((column: any) => {
    const flag = showRoleColumn();
    if (!flag && column.title === '操作') {
      return false;
    }
    return true;
  });
});
const loading = ref<boolean>(false);
// 数据处理
const data = ref<DatalistItem[]>([]);
const editableData: UnwrapRef<Record<string, any>> = reactive({});
const searchKeyword = ref<string>('');
const visible = ref<boolean>(false);
const formRef = ref<any>(null);

// 获取全部数据
async function fetchData() {
  loading.value = true;
  try {
    // 首先获取指标数据
    const response1: any = await getindicators();
    const indicatorsData = response1.data;

    // 创建一个映射来存储数据，以 mainIndicator 作为键
    const dataMap = new Map();

    // 处理 response1 数据
    indicatorsData.forEach((item: { mainIndicator: any }) => {
      dataMap.set(item.mainIndicator, { ...item });
    });

    // 遍历指标数据，对于每个指标，根据其mainIndicator获取相关部门数据
    for (const indicator of indicatorsData) {
      // 调用 queryByConditions 接口获取数据
      const response2: any = await queryByConditions({ mainIndicator: indicator.mainIndicator });
      const departmentData = response2.data;
      // 处理 response2 数据
      departmentData.forEach((department: { [x: string]: any, mainIndicator?: any }) => {
        if (dataMap.has(department.mainIndicator)) {
          // 如果映射中已有该 mainIndicator，合并数据
          const existingItem = dataMap.get(department.mainIndicator);
          // 只添加 response2 中独有的字段
          Object.keys(department).forEach((key) => {
            if (!(key in existingItem)) {
              existingItem[key] = department[key];
            }
          });
        }
        else {
          // 如果映射中没有该 mainIndicator，添加新数据
          dataMap.set(department.mainIndicator, { ...department });
        }
      });
    }

    // 将映射转换为数组
    const combinedData = Array.from(dataMap.values());

    // 将最终合并的数据赋值给 data
    data.value = mergeCellsByKey(combinedData, 'evaluationItem');
  }
  catch (error) {
    message.error('数据获取失败！');
  }
  finally {
    loading.value = false;
  }
}

// 单元格合并
function mergeCellsByKey(data: any[], key: string) {
  const rowSpanMap: any = {};
  data.forEach((item: { [x: string]: any }, index: number) => {
    const value = item[key];
    if (!rowSpanMap[value]) {
      rowSpanMap[value] = { count: 0, indexes: [] };
    }
    rowSpanMap[value].count += 1;
    rowSpanMap[value].indexes.push(index);
  });

  data.forEach((item: { [x: string]: any }, index: number) => {
    const value = item[key];
    const entry = rowSpanMap[value];
    item[`${key}RowSpan`] = entry.indexes[0] === index ? entry.count : 0;

    // 通过设置样式来隐藏第二个及以后的单元格
    if (entry.indexes[0] !== index) {
      item.style = { display: 'none' }; // 隐藏
    }
    else {
      item.style = { display: '' }; // 显示
    }
  });

  return data;
}

// 查询功能
async function onSearch(searchKeyword: string) {
  try {
    const response: any = await search({ evaluationItem: searchKeyword });
    // data.value=response.data;
    data.value = mergeCellsByKey(response.data, 'evaluationItem');
    message.success('搜索成功');
  }
  catch (error) {
    message.error('按关键词搜索失败');
  }
}

interface DatalistItem {
  id: number
  evaluationItem: string
  mainIndicator: string
  mainIndicatorScore: string
  dataProvisionDepartment: string
  evaluationPeriod: string
  targetValue: string
  indicatorDefinition: string
  deductionAdditionMethod: string
}

// 表单数据
const formData = reactive({
  evaluationItem: '',
  mainIndicator: '',
  mainIndicatorScore: '',
  dataProvisionDepartment: '',
  evaluationPeriod: '',
  targetValue: '',
  indicatorDefinition: '',
  deductionAdditionMethod: '',
});

// 删除数据
async function onDelete(id: number) {
  Modal.confirm({
    title: () => '确定要删除吗？',
    okText: () => '是的',
    okType: 'danger',
    cancelText: () => '取消',
    onOk() {
      data.value = data.value.filter((item: { id: number }) => item.id !== id);
      // 重新合并单元格
      data.value = mergeCellsByKey(data.value, 'evaluationItem');
      deleteSingleRecord([id]);
    },
  });
}

async function deleteSingleRecord(id: number[]) {
  try {
    await deleteindicators(id);
    message.success('记录删除成功');
  }
  catch (error) {
    message.error('删除失败');
  }
}

// 编辑数据
function edit(id: number) {
  editableData[id] = cloneDeep(data?.value?.filter((item: { id: number }) => id === item.id)[0]);
  // editableData[id]= cloneDeep(data?.value?.find((item:{id:number}) => id === item.id));
}

// 保存
async function save(id: number) {
  const newData = Object.assign(data?.value?.filter((item: { id: number }) => id === item.id)[0], editableData[id]);
  const updateData1 = {
    id: newData.id,
    evaluationItem: newData.evaluationItem,
    mainIndicator: newData.mainIndicator,
    mainIndicatorScore: newData.mainIndicatorScore,
    dataProvisionDepartment: newData.dataProvisionDepartment,
    evaluationPeriod: newData.evaluationPeriod,
    targetValue: newData.targetValue,
    indicatorDefinition: newData.indicatorDefinition,
    deductionAdditionMethod: newData.deductionAdditionMethod,
  };
  const updateData2 = {
    id: newData.id,
    evaluationItem: newData.evaluationItem,
    mainIndicator: newData.mainIndicator,
    dataProvisionDepartment: newData.dataProvisionDepartment,
    yuecheng: newData.yuecheng,
    keqiao: newData.keqiao,
    shangyu: newData.shangyu,
    shengzhou: newData.shengzhou,
    xinchang: newData.xinchang,
    zhuji: newData.zhuji,
  };
  try {
    // 调用第一个接口更新数据
    await updateindicators(updateData1);
    // 调用第二个接口更新数据
    await update(updateData2);
    message.success('修改成功');
    // 从 editableData 中删除已保存的数据项
    delete editableData[id];
    // 重新加载数据
    // fetchData();
  }
  catch (error) {
    message.error('修改失败');
  }
  // delete editableData[id];
}

// 取消编辑
function cancel(id: number) {
  delete editableData[id];
}

// 跳转
function linkObject(mainIndicator: any) {
  return { name: 'assessmentIndicatorsMonthDetails', query: { mainIndicator } };
}

// 添加数据
function add() {
  visible.value = true;
}
async function handleOk() {
  try {
    // 触发表单验证
    if (formRef.value) {
      await formRef.value.validate();
    }
    // 表单验证通过后，调用 API 插入数据
    await addindicators(formData);
    message.success('数据添加成功');
    // 关闭模态框
    visible.value = false;
    // 重新加载数据
    fetchData();
  }
  catch (error) {
    // 表单验证失败，显示错误消息
    message.error('请检查表单输入!');
  }
}

onMounted(() => {
  fetchData();
});
function isEdit() {
  return auth([
    'a_i_exitquota',
  ]);
}
// excel文件上传
const fileList = ref<any>([]);

// 移除文件
function handleRemove(file: any) {
  const index = fileList.value.findIndex((f: { uid: any }) => f.uid === file.uid);
  fileList.value.splice(index, 1);
}

// 阻止自动上传
function beforeUpload(file: any) {
  fileList.value = [];
  fileList.value.push(file);
  return false; // 阻止自动上传
}

// 手动上传
async function handleManualUpload() {
  if (fileList.value.length === 0) {
    message.error('请上传文件！');
    return;
  }
  fileList.value.forEach(async (file: any) => {
    // 判断文件类型
    if (useUpload().checkIfExcel(file.name || '')) {
      // loading.value = true;
      const formData = new FormData();
      formData.append('file', file);
      const reader = new FileReader();
      reader.onload = async (e) => {
        const buffer: any = e.target?.result;
        if (buffer) {
          const workbook = new ExcelJS.Workbook();
          await workbook.xlsx.load(buffer).then(async () => {
            // 上传到数据库
            await addYunwangWorkEvaluationIndicatorsAndDataFileupload(formData).then(async () => {
              message.success('上传成功！');
              // 移除文件
              handleRemove(file);
              // 更新数据
              fetchData();
            })
              .catch(async () => {
                message.error('上传失败');
                // 重新更新数据，将原先显示在页面的数据撤回
                fetchData();
              });
          });
        }
      };
      reader.readAsArrayBuffer(file);
    }
    else {
      message.error('请上传execl文件！');
    }
  });
}

// 日期
const datePicker = ref<any>(null);

function changeTime() {
  nextTick(() => {
    if (datePicker.value) {
      datePicker.value.blur();
    }
  });
}

function getCurrentYearMonth(): string {
  // 获取当前年月
  const now = new Date();
  const year = now.getFullYear();
  const month = (now.getMonth() + 1).toString().padStart(2, '0');
  return `${year}年${month}月`;
}
const year = ref<any>(getCurrentYearMonth());
const yearMonth = ref<any[]>();
async function getYearMonth() {
  await useKPIHistoryStore().getKpiList();
  yearMonth.value = useKPIHistoryStore().kpiList;
}
onMounted(async () => {
  await getYearMonth();
});
function disabledDate(current: dayjs.Dayjs) {
  // return current && current < moment().endOf('day');

  const currentYearMonth = `${current.year()}${(`0${current.month() + 1}`).slice(-2)}`;
  let flag = false;
  if (yearMonth.value) {
    for (let i = 0; i < yearMonth.value.length; i++) {
      const yearMonthDate = yearMonth.value[i].yearMonth.replace(/年/g, '').replace(/月/g, '').replace(/^(\d{4})(\d)$/, (_: any, year: any, month: string) => `${year}${month.padStart(2, '0')}`);
      if (currentYearMonth === yearMonthDate) {
        flag = true;
      }
    }
  }
  return flag;
}
</script>

<template>
  <PubPageMain class="max">
    <div class="header">
      <div class="left">
        <a-space>
          <div class="pjTitle">
            区县月度评价考核
          </div>
          <a-button v-auth="'a_i_add'" type="link" @click="add">
            新增
          </a-button>
          <a-button type="link" @click="$router.push('/assessment_indicators/month/history')">
            历史记录
          </a-button>
          <a-modal
            v-model:visible="visible" title="插入数据" :closable="false" :mask-closable="false"
            :focus-trigger-after-close="false" @ok="handleOk"
          >
            <a-form ref="formRef" :model="formData" layout="vertical" @submit.prevent>
              <a-form-item
                label="考核项目" name="evaluationItem"
                :rules="[{ required: true, message: '考核项目不能为空', trigger: 'blur' }]"
              >
                <a-input v-model:value="formData.evaluationItem" />
              </a-form-item>
              <a-form-item
                label="大指标" name="mainIndicator"
                :rules="[{ required: true, message: '大指标不能为空', trigger: 'blur' }]"
              >
                <a-input v-model:value="formData.mainIndicator" />
              </a-form-item>
              <a-form-item label="大指标分值" name="mainIndicatorScore">
                <a-input v-model:value="formData.mainIndicatorScore" />
              </a-form-item>
              <a-form-item label="考核部门的提供部门和取数据的系统" name="dataProvisionDepartment">
                <a-input v-model:value="formData.dataProvisionDepartment" />
              </a-form-item>
              <a-form-item label="考核周期" name="evaluationPeriod">
                <a-input v-model:value="formData.evaluationPeriod" />
              </a-form-item>
              <a-form-item label="目标值" name="targetValue">
                <a-input v-model:value="formData.targetValue" />
              </a-form-item>
              <a-form-item label="指标定义(解释)" name="indicatorDefinition">
                <a-input v-model:value="formData.indicatorDefinition" />
              </a-form-item>
              <a-form-item label="扣加分方法" name="deductionAdditionMethod">
                <a-input v-model:value="formData.deductionAdditionMethod" />
              </a-form-item>
            </a-form>
          </a-modal>
          <a-input-search
            v-model="searchKeyword" v-auth="'e-details-search'" placeholder="请输入考核项目" enter-button
            style="width: 200px;" @search="onSearch"
          />
        </a-space>
      </div>
      <div class="right">
        <a-space>
          <div>
            <a-date-picker
              ref="datePicker" v-model:value="year" picker="month" value-format="YYYY年MM月"
              format="YYYY年MM月" :bordered="false" :allow-clear="false" input-read-only :disabled-date="disabledDate"
              @change="changeTime"
            >
              <template #suffixIcon />
            </a-date-picker>
          </div>
          <a-upload
            v-auth="'e-index-upload'" :file-list="fileList" :before-upload="beforeUpload" name="file"
            :multiple="false" action="" accept=".xlsx, .xls" :on-remove="handleRemove"
          >
            <a-button>
              <upload-outlined /> 点击选择文件
            </a-button>
          </a-upload>
          <a-button v-auth="'e-index-upload'" type="primary" @click="handleManualUpload">
            上传
          </a-button>
          <a-button type="primary">
            定稿
          </a-button>
          <a-button type="primary" @click="useDownExcel().downKpiExcel()">
            导出为excel
          </a-button>
        </a-space>
      </div>
    </div>
    <div class="content">
      <a-table
        :columns="columns" :data-source="data" :scroll="{ x: 2600 }" class="k-table" :pagination="false"
        :loading="loading"
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex === 'operation'">
            <div class="editable-row-operations">
              <span v-if="editableData[record.id]">
                <a-typography-link @click="save(record.id)">保存</a-typography-link>
                <a @click="cancel(record.id)">取消</a>
              </span>
              <span v-else>
                <a-space>
                  <RouterLink :to="linkObject(record.mainIndicator)">查看详情</RouterLink>
                  <a @click="edit(record.id)">编辑</a>
                  <a @click="onDelete(record.id)">删除</a>
                </a-space>
              </span>
            </div>
          </template>
          <template v-else>
            <div>
              <div v-if="isEdit()">
                <a-input
                  v-if="editableData[record.id]"
                  v-model:value="editableData[record.id][column.dataIndex as string]" style="margin: -5px 0;"
                />
                <template v-else>
                  {{ text }}
                </template>
              </div>
              <div v-else>
                <a-input
                  v-if="editableData[record.id] && ['yuecheng', 'keqiao', 'shangyu', 'shengzhou', 'xinchang', 'zhuji'].includes(column.dataIndex as string)"
                  v-model:value="editableData[record.id][column.dataIndex as string]" style="margin: -5px 0;"
                />
                <template v-else>
                  {{ text }}
                </template>
              </div>
            </div>
          </template>
        </template>
      </a-table>
    </div>
  </PubPageMain>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;
  overflow: auto;

  .header {
    position: sticky;
    top: 0;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 40px;
    margin-bottom: 10px;
    background-color: #fff;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .editable-row-operations a {
    margin-right: 8px;
  }

  .content {
    display: flex;
    flex: 1;
    flex-direction: column;
    width: 100%;
    height: 95%;
    overflow: auto;
    overflow-y: auto;

    .k-table {
      flex-grow: 1;
      height: 100%;
      max-height: 100%;
      padding: 10px;
    }
  }
}
</style>
